<?php

class Upload extends CActiveRecord
{
	public $categoria;
	
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return 'upload';
	}

	public function rules()
	{
		return array(
			array('data, id_usuario_fk, arquivos, categoria', 'required'),
			array('id_usuario_fk, excluido', 'numerical', 'integerOnly'=>true),
			array('id_upload, data, id_usuario_fk, excluido, categoria', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
			'arquivos' => array(self::HAS_MANY, 'Arquivo', 'id_upload_fk'),
			'idUsuarioFk' => array(self::BELONGS_TO, 'Usuario', 'id_usuario_fk'),
		);
	}
	
	public function attributeLabels()
	{
		return array(
			'id_upload' => 'Id Upload',
			'data' => 'Data',
			'categoria' => 'Categoria',
			'id_usuario_fk' => 'Id Usuario Fk',
			'excluido' => 'Excluido',
		);
	}
	
	protected function afterFind()
	{
		$this->data=date('d/m/Y', strtotime($this->data));
		return TRUE;
	}
	
	public function deletar()
	{
		foreach ($this->arquivos as $file)
		{
			$file->excluido = 1;
			$file->update();
		}
		$this->excluido = 1;
		$this->update();
		return true;
	}

	public function buscarUpload()
	{
		$criteria=new CDbCriteria;
		$criteria->alias = 'Upload';
		$criteria->condition = 'Upload.id_usuario_fk = ' . Usuario::getUsuario()->id_usuario . " AND Upload.excluido = 0";
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function buscarArquivos()
	{
		$criteria=new CDbCriteria;
		$criteria->alias = 'Arquivo';
		$criteria->condition = 'Arquivo.id_upload_fk = ' . $this->id_upload . " AND Arquivo.excluido = 0";
		$arquivo = new Arquivo;
		return new CActiveDataProvider($arquivo, array(
			'criteria'=>$criteria,
		));	
	}
	
}